package com.baiyun.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Data
@Component
@RequiredArgsConstructor
public class AliOSSUtils {

    private final AliOSSProperties aliOSSProperties;
    /**
     * 实现上传图片到OSS
     */
    public String uploadFile(MultipartFile multipartFile) throws IOException {

        String endpoint = aliOSSProperties.getEndpoint();
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();
        //获取上传文件的输入流
        InputStream inputStream = multipartFile.getInputStream();
        //使用UUID生成文件名称，避免重名被覆盖
        String uuid = UUID.randomUUID().toString();
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = uuid + originalFilename.substring(originalFilename.lastIndexOf("."));
        //创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //上传文件到阿里云OSS
        ossClient.putObject(bucketName, fileName, inputStream);
        //拼接文件访问路径
        String fileUrl = endpoint.split("//")[0] + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        //关闭OSSClient
        ossClient.shutdown();
        return fileUrl;
    }
}
